<?php

namespace app\admin\controller\workorder;

use think\Db;
use Exception;
use think\exception\PDOException;
use app\common\controller\Backend;
use addons\workorder\model\Engineer;
use addons\workorder\library\General;
use think\exception\ValidateException;
use app\admin\model\workorder\Records;

/**
 * 工单管理
 */
class Orders extends Backend
{
    /**
     * Orders模型对象
     * @var \app\admin\model\workorder\Orders
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\workorder\Orders();
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 查看
     */
    public function index()
    {
        $fieldsList = \app\admin\model\workorder\Fields::where('status', 1)
            ->where('position', 0)
            ->where('type_list', '<>', 'text')
            ->select();
        $fields     = [];
        foreach ($fieldsList as $item) {
            if ($item['isfilter']) {
                $fields[] = [
                    'field'  => $item['name'],
                    'title'  => $item['title'],
                    'type'   => $item['type_list'],
                    'values' => $item['values_list']
                ];
            }
        }
        $this->assignconfig('fields', $fields);

        // 当前是否为关联查询
        $this->relationSearch = true;
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->with(['user', 'engineers', 'category', 'urgentrank'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname']);
                $row->getRelation('urgentrank')->visible(['name']);
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('engineers')->visible(['title']);
            }

            return json(["total" => $list->total(), "rows" => $list->items()]);
        }
        return $this->view->fetch();
    }

    public function records($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $allField   = $this->model->getFields($row, 0);
        $basicField = [];// 工单基本信息字段
        $listField  = ['select', 'selects', 'checkbox', 'radio'];
        foreach ($allField as $field) {
            if ($field['isbasicinfo'] == 1) {
                if (in_array($field['type_list'], $listField)) {
                    if (is_array($field['values_list'])) {
                        $field['value'] = $field['values_list'][$field['value']] ?? '';
                    }
                }
                $basicField[] = $field;
            }
        }

        $basicField[] = [
            'title' => '提交用户',
            'value' => $row->user->nickname
        ];

        $row->status       = __('Status ' . $row->status);
        $row->createtime   = human_date($row->createtime);
        $row->user->avatar = ($row->user && $row->user->avatar) ? cdnurl($row->user->avatar, true) : (function_exists('letter_avatar') ? letter_avatar($row->user->nickname) : cdnurl('/assets/img/avatar.png', true));

        // 沟通记录
        $records = Records::where('order_id', $row->id)->order('createtime asc')->select();

        // 共有哪些工程师
        $engineers = [];
        if ($row->engineer_id) {
            $engineers[$row->engineer_id] = $row->engineer_id;
        }
        foreach ($records as $record) {
            if ($record->engineer_id) {
                $engineers[$record->engineer_id] = $record->engineer_id;
            }
            if ($record->engineer && $record->engineer->user) {
                $record->engineer->user->avatar = $record->engineer->user->avatar ?: (function_exists('letter_avatar') ? letter_avatar($record->engineer->title) : cdnurl('/assets/img/avatar.png', true));
            }
        }
        $engineers          = Engineer::select($engineers);
        $engineerInfoConfig = Engineer::getEngineerInfoConfig();
        foreach ($engineers as $engineer) {
            if (!$engineer->introduce) {
                $engineer->introduce = ($engineer->user && $engineer->user->bio) ? $engineer->user->bio : '';
            }
            $engineer->all_order_number = in_array('all_order_number', $engineerInfoConfig) ? $engineer->all_order_number : false;
            $engineer->wx               = in_array('wx', $engineerInfoConfig) ? $engineer->wx : false;
            $engineer->qq               = in_array('qq', $engineerInfoConfig) ? $engineer->qq : false;
            if ($engineer->user) {
                $engineer->user->mobile = in_array('mobile', $engineerInfoConfig) ? $engineer->user->mobile : false;
                $engineer->user->email  = in_array('email', $engineerInfoConfig) ? $engineer->user->email : false;
                $engineer->user->avatar = $engineer->user->avatar ?: (function_exists('letter_avatar') ? letter_avatar($engineer->title) : cdnurl('/assets/img/avatar.png', true));
            }
        }

        $this->view->assign('row', $row);
        $this->view->assign('records', $records);
        $this->view->assign('engineers', $engineers);
        $this->view->assign('basicField', $basicField);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($params['engineer_id']) {
                    $engineer = \app\admin\model\workorder\Engineers::get($params['engineer_id']);
                    if (!$engineer->user_id) {
                        $this->error(__('The specified responsible engineer is not bound to the user!'));
                    } elseif ($engineer->user_id == $params['user_id']) {
                        $this->error(__('Bill of lading user and responsible engineer cannot be the same member!'));
                    }
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $general = General::instance();
                $res     = $general->createOrder($params, $params['user_id']);
                if ($res['code'] == 1) {
                    $this->success();
                } else {
                    $this->error($res['msg']);
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign('fields', $this->model->getFields(null, 0));
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 修改了工程师或用户
                if (($params['engineer_id'] != $row['engineer_id']) || ($params['user_id'] != $row['user_id'])) {
                    $engineer = \app\admin\model\workorder\Engineers::get($params['engineer_id']);
                    if (!$engineer) {
                        $this->error(__('Please select the responsible engineer!'));
                    }
                    if (!$engineer->user_id) {
                        $this->error(__('The specified responsible engineer is not bound to the user!'));
                    } elseif ($engineer->user_id == $params['user_id']) {
                        $this->error(__('Bill of lading user and responsible engineer cannot be the same member!'));
                    }
                }

                // 分派了工程师
                if (!$row['engineer_id'] && $params['engineer_id'] && $row['status'] == 0) {
                    $params['status'] = 1;
                }

                foreach ($params as $key => $item) {
                    if (is_array($item)) {
                        $params[$key] = implode(',', $item);
                    }
                }

                $result = false;
                Db::startTrans();
                try {

                    if (($params['engineer_id'] != $row['engineer_id']) && isset($engineer)) {
                        $engineer->lastreceivetime = time();
                        $engineer->work_order_quantity++;
                        $engineer->save();

                        $record = [
                            'order_id'     => $row['id'],
                            'engineer_id'  => $row['engineer_id'],
                            'message_type' => 3,
                            'message'      => __('The work order has been transferred to:%s', $engineer->title)
                        ];
                        Records::create($record);
                    }

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException()->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign('fields', $this->model->getFields($row, 0));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if ($ids) {
            $pk       = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $v) {
                    $count += $v->delete();
                    General::orderNumberChangeCalcEngineerStatistics($v->id, $v->engineer_id);
                }
                Db::commit();
            } catch (PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 还原
     */
    public function restore($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids      = $ids ?: $this->request->post("ids");
        $pk       = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $count += $item->restore();
                General::orderNumberChangeCalcEngineerStatistics($item->id, $item->engineer_id, 'restore');
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

}
